package com.hmall.item.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmall.common.constant.ItemStatusConstants;
import com.hmall.common.constant.MQConstants;
import com.hmall.common.domain.PageDTO;
import com.hmall.common.domain.PageQuery;
import com.hmall.common.utils.BeanUtils;
import com.hmall.item.domain.dto.ItemDTO;
import com.hmall.item.domain.dto.OrderDetailDTO;
import com.hmall.item.domain.po.Item;
import com.hmall.item.domain.po.ItemDoc;
import com.hmall.item.service.IItemService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

@Api(tags = "商品管理相关接口")
@RestController
@RequestMapping("/items")
@RequiredArgsConstructor
public class ItemController {

    private final IItemService itemService;

    private final RabbitTemplate rabbitTemplate;

    @ApiOperation("分页查询商品")
    @GetMapping("/page")
    public PageDTO<ItemDTO> queryItemByPage(PageQuery query) {
        // 1.分页查询
        Page<Item> result = itemService.page(query.toMpPage("update_time", false));
        // 2.封装并返回
        return PageDTO.of(result, ItemDTO.class);
    }

    @ApiOperation("根据id批量查询商品")
    @GetMapping
    public List<ItemDTO> queryItemByIds(@RequestParam("ids") List<Long> ids){
        return itemService.queryItemByIds(ids);
    }

    @ApiOperation("根据id查询商品")
    @GetMapping("{id}")
    public ItemDTO queryItemById(@PathVariable("id") Long id) {
        return BeanUtils.copyBean(itemService.getById(id), ItemDTO.class);
    }

    @ApiOperation("新增商品")
    @PostMapping
    public String saveItem(@RequestBody ItemDTO item) {
        // 新增
        item.setStatus(ItemStatusConstants.ON_SALE);
        item.setIsAD(true);
        itemService.save(BeanUtils.copyBean(item, Item.class));
        Item saveItem = itemService.getOne(new QueryWrapper<Item>()
                .eq("name", item.getName())
                .eq("price", item.getPrice())
                .eq("category", item.getCategory()));
        item.setId(saveItem.getId());
        rabbitTemplate.convertAndSend(
                MQConstants.ITEM_EXCHANGE_DIRECT_NAME,
                MQConstants.ITEM_CREATE_ROUTING_KEY,
                BeanUtils.copyBean(item, ItemDoc.class));
        return "新增商品成功!";
    }

    @ApiOperation("更新商品状态")
    @PutMapping("/status/{id}/{status}")
    public String updateItemStatus(@PathVariable("id") Long id, @PathVariable("status") Integer status){
        Item item = new Item();
        item.setId(id);
        item.setStatus(status);
        itemService.updateById(item);
        item = itemService.getById(id);
        if (Objects.equals(status, ItemStatusConstants.ON_SALE)){
            rabbitTemplate.convertAndSend(
                    MQConstants.ITEM_EXCHANGE_DIRECT_NAME,
                    MQConstants.ITEM_CREATE_ROUTING_KEY,
                    BeanUtils.copyBean(item, ItemDoc.class)
            );
            return "上架成功!";
        }else {
            rabbitTemplate.convertAndSend(
                    MQConstants.ITEM_EXCHANGE_DIRECT_NAME,
                    MQConstants.ITEM_DELETE_ROUTING_KEY,
                    id
            );
            return "下架成功!";
        }
    }

    @ApiOperation("更新商品")
    @PutMapping
    public String updateItem(@RequestBody ItemDTO item) {
        // 不允许修改商品状态，所以强制设置为null，更新时，就会忽略该字段
        item.setStatus(null);
        // 更新
        itemService.updateById(BeanUtils.copyBean(item, Item.class));
        Integer status = itemService.getById(item.getId()).getStatus();
        if (Objects.equals(status, ItemStatusConstants.ON_SALE)){
            rabbitTemplate.convertAndSend(
                    MQConstants.ITEM_EXCHANGE_DIRECT_NAME,
                    MQConstants.ITEM_UPDATE_ROUTING_KEY,
                    BeanUtils.copyBean(item, ItemDoc.class)
            );
        }
        return "更新商品成功!";
    }

    @ApiOperation("根据id删除商品")
    @DeleteMapping("{id}")
    public String deleteItemById(@PathVariable("id") Long id) {
        Integer status = itemService.getById(id).getStatus();
        itemService.removeById(id);
        if (Objects.equals(status, ItemStatusConstants.ON_SALE)) {
            rabbitTemplate.convertAndSend(
                    MQConstants.ITEM_EXCHANGE_DIRECT_NAME,
                    MQConstants.ITEM_DELETE_ROUTING_KEY,
                    id
            );
        }
        return "删除商品成功!";
    }

    @ApiOperation("批量扣减库存")
    @PutMapping("/stock/deduct")
    public void deductStock(@RequestBody List<OrderDetailDTO> items){
        itemService.deductStock(items);
    }

    @ApiOperation("批量恢复库存")
    @PutMapping("/stock/restore")
    public void restoreStock(@RequestBody List<OrderDetailDTO> items) {
        itemService.restoreStock(items);
    }
}
